package com.xinyi.shicihui.service.impl;

import com.xinyi.shicihui.dao.ShiciInfoDao;
import com.xinyi.shicihui.dao.ShirenDao;
import com.xinyi.shicihui.dao.ShirenInfoDao;
import com.xinyi.shicihui.pojo.entity.ShiciInfo;
import com.xinyi.shicihui.pojo.entity.Shiren;
import com.xinyi.shicihui.pojo.entity.ShirenInfo;
import com.xinyi.shicihui.pojo.vo.ShiciInfoVo;
import com.xinyi.shicihui.pojo.vo.ShirenDetailVo;
import com.xinyi.shicihui.pojo.vo.ShirenInfoVo;
import com.xinyi.shicihui.pojo.vo.ShirenVo;
import com.xinyi.shicihui.service.ShirenService;
import com.xinyi.shicihui.utils.BeanMapperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author xinyi
 * @desc 诗人信息实现类
 * @date 2022/1/25
 */
@Service
public class ShirenServiceImpl implements ShirenService {
    @Autowired
    private ShirenDao shirenDao;
    @Autowired
    private ShirenInfoDao shirenInfoDao;

    @Override
    public Page<Shiren> pageQuery(Integer page, Integer size, String dynastyId) {
        Shiren shiren = new Shiren();
        shiren.setDynastyId(dynastyId);
        ExampleMatcher matcher = ExampleMatcher.matching();
        Example<Shiren> example = Example.of(shiren, matcher);

        return "-1".equals(dynastyId) ? shirenDao.findAll(PageRequest.of(page, size)) :
                shirenDao.findAll(example, PageRequest.of(page - 1, size));
    }

    @Override
    public ShirenDetailVo detail(String id) {

        Optional<Shiren> shirenOptional = shirenDao.findById(id);
        if (!shirenOptional.isPresent()) {
            return new ShirenDetailVo();
        }
        List<ShirenInfo> shirenInfos = shirenInfoDao.findByAuthorId(id);
        ShirenDetailVo shirenDetailVo = new ShirenDetailVo();
        shirenDetailVo.setShiren(BeanMapperUtils.map(shirenOptional.get(), ShirenVo.class));
        shirenDetailVo.setInfo(BeanMapperUtils.mapList(shirenInfos, ShirenInfoVo.class));
        return shirenDetailVo;
    }
}
